package com.woniuxy.sddfp.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.sddfp.common.exception.Assert;
import com.woniuxy.sddfp.common.model.dto.user.UserRegisterDto;
import com.woniuxy.sddfp.common.result.enums.impl.BusinessCode;
import com.woniuxy.sddfp.system.entity.User;
import com.woniuxy.sddfp.system.entity.UserDetail;
import com.woniuxy.sddfp.system.mapper.UserMapper;
import com.woniuxy.sddfp.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yellow doctor
 * @since 2025-06-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserDetailServiceImpl userDetailService;
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //1.判断这个手机号是否已注册
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, userRegisterDto.getPhone()));
        Assert.error(Objects.nonNull(user), BusinessCode.USER_EXISTED);
        registerUser(userRegisterDto);
    }

    private void registerUser(UserRegisterDto userRegisterDto) {
        User user1 = new User();
        user1.setUserName(userRegisterDto.getUserName());
        user1.setPhone(userRegisterDto.getPhone());
        //密码加密
//        String hashpw = BCrypt.hashpw(userRegistDto.getPwd());
//        BCrypt.checkpw(userRegistDto.getPwd(), hashpw);
        user1.setPwd(userRegisterDto.getPwd());
        user1.setUserType("1");
        save(user1);

        //3、添加userDetail对象
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user1.getId());
        userDetail.setUserName(userRegisterDto.getUserName());
        userDetail.setPhone(userRegisterDto.getPhone());
        userDetail.setBorrowMoney(new BigDecimal("0"));
        //用户码 随机数   UUID.randomUUID().toString().substring(0,12) 截取 12 位
        userDetail.setUserCode("UC_" + UUID.randomUUID().toString().substring(0, 12));
        //是否绑卡 默认未绑卡 false
        userDetail.setCardBindStatus(false);

        userDetailService.save(userDetail);

    }
}
